import { Injectable } from '@angular/core';
import {Subject} from 'rxjs';
import {FormGroup} from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  // 保存form表单
  formInst = null;

  /* 用来保存当前选中的FormGroup、FormControl、FormArray对象 */
  formGroupInst: object = {};
  formControlInst: object = {};
  formArrayInst: object = {};

  /* 保存form表单的树状结构 */
  formTree = null;
  formTreeSubject = new Subject<object>();

  // 保存form表单的层级关系
  relationShip = null;

  // 保存当前获取的表单节点
  formNodeSubject = new Subject<object>();

  formControlSubject = new Subject<object>();
  formGroupSubject = new Subject<object>();
  formArraySubject = new Subject<object>();

  constructor() { }

  /**
   * 获取表单子元素实例
   * @param type(string) ：类型， 有三种： formGroup、formControl、formArray
   * @param name(string) ：名称
   * @param formGroup(FormGroup) ：当前的FormGroup，在递归循环时使用它来获取子控件
   * @param operate(string) ：操作，也就是获取节点的用途，例如用于设置父控件setParentNode
   */
  getFormNodeInstance(type, name, formGroup: FormGroup = this.formInst, operate?) {
    if (name === 'profileForm') {
      this.formNodeSubject.next({
        type,
        name,
        operate,
        instance: formGroup
      });
    } else {
      if (formGroup.get(name)) {
        this.formNodeSubject.next({
          type,
          name,
          operate,
          instance: formGroup.get(name)
        });
      } else {
        const controls = formGroup.controls;
        for (const key of Object.keys(controls)) {
          const childNode = controls[key];
          if (childNode instanceof FormGroup) {
            this.getFormNodeInstance(type, name, childNode);
          }
        }
      }
    }
  }

  // 输出类型转换
  convertType(content) {
    const type = typeof content;
    let result;

    switch (type) {
      case 'number':
        result = content;
        break;
      case 'function':
        result = content.toString();
        break;
      default:
        result = JSON.stringify(content);
        break;
    }

    return result;
  }
}
